//
//  XZLErrorRequestStateView.m
//  XZLife
//
//  Created by liangshangjia on 15/11/9.
//  Copyright (c) 2015年 Sami-industry. All rights reserved.
//

#import "SMRequestStateView.h"
static NSString *kXZLErrorRequestStateViewAnimationKey = @"kXZLErrorRequestStateViewAnimationKey";

@interface SMRequestStateView ()
@property (nonatomic, strong) UILabel *stateLB;  //状态方案
@property (nonatomic, strong) UIImageView *noticeIcon; //警示图标
@property (nonatomic, strong) UIImageView *animatingIV;
@property (nonatomic, strong) UIImageView *animatingOutIV;

@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong) UIView *backgroundView;
@end

@implementation SMRequestStateView {
    NSString *_errorText;
    NSString *_activityText;
    BOOL _aniamting;
    BOOL _hiding;
}


- (instancetype)init {
    if (self = [super init]) {
        [self customInit];
    }
    return self;
}

- (void)customInit {

    _errorText = @"呀，网络出问题了";
    _activityText = @"";

    _backgroundView = [UIView new];
    _backgroundView.backgroundColor = HEXCOLOR(@"#F6F6F6");
    [self addSubview:_backgroundView];
    [_backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];


    CGPoint point = CGPointMake(SM_SCREEN_WIDTH, SM_SCREEN_HEIGHT);
    [[[UIApplication sharedApplication] keyWindow] convertPoint:point toView:self];

    _noticeIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ic_network_error"]];
    [_noticeIcon setContentMode:UIViewContentModeScaleAspectFill];
    [self addSubview:self.noticeIcon];
    [self.noticeIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.top.equalTo(@(64+SM_SIZE(200)));
    }];

    _stateLB = [[UILabel alloc]init];
    _stateLB.textColor = HEXCOLOR(@"#242424");
    _stateLB.font = SM_CFont(32);
    _stateLB.textAlignment = NSTextAlignmentCenter;
    _stateLB.numberOfLines = 0;
    [self addSubview:self.stateLB];
    [self.stateLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(SM_SIZE(30)));
        make.right.equalTo(@(SM_SIZE(-30)));
        make.top.equalTo(self.noticeIcon.mas_bottom).offset(SM_SIZE(50));
    }];


    _animatingIV = [[UIImageView alloc]init];//WithImage:[UIImage imageNamed:@"ic_loading_indicator"]];
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:6];
    for (NSUInteger i = 1; i <= 5; i ++) {
        [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"loading%li",i]]];
    }
    _animatingIV.animationImages = images;
    _animatingIV.animationDuration = 1.f;

    [self addSubview:_animatingIV];
    _animatingIV.frame = CGRectMake(0, 0, SM_SIZE(190), SM_SIZE(190));

    [_animatingIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.mas_centerY);
        make.centerX.equalTo(self.mas_centerX);
        make.width.height.equalTo(@(SM_SIZE(190)));
    }];


    _button = [UIButton new];
    [_button setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
    [_button setTitle:@"重新加载" forState:UIControlStateNormal];
    [_button.titleLabel setFont:SM_CFont(35)];
    [_button.layer setCornerRadius:5];
    _button.clipsToBounds = YES;
    [_button addTarget:self action:@selector(onClickView:) forControlEvents:UIControlEventTouchUpInside];
    [_button setTitleColor:SM_blackColor forState:UIControlStateNormal];
    [self addSubview:_button];
    [_button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@(SM_SIZE(250)));
        make.height.equalTo(@(SM_SIZE(90)));
        make.top.equalTo(_stateLB.mas_bottom).offset(SM_SIZE(50));
        make.centerX.equalTo(self.mas_centerX);
    }];

}


- (void)layoutSubviews
{
    [super layoutSubviews];
    /*
    CGPoint point = [SMKeyWindow convertPoint:CGPointMake(SM_SCREEN_WIDTH/2, SM_SCREEN_HEIGHT/2) toView:self];
    NSLog(@"%@",NSStringFromCGPoint(point));
    _animatingIV.center = point;*/
}

- (id)animation {
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    animation.values = @[@(0),@(M_PI/2)/*,@(M_PI)*/,@(M_PI),@(M_PI/2.f*3)/*,@(2*M_PI)*/];
    animation.duration = .7;
    animation.autoreverses = NO;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
    animation.repeatCount = MAXFLOAT;
    return animation;
}

- (CABasicAnimation *)animationOut
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = .2;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    return animation;
}

- (void)startAnimating:(NSString *)state {
    if (_aniamting) {
        return;
    }
    _aniamting = YES;
    self.alpha = 1;
    self.animatingIV.hidden = NO;
    self.animatingOutIV.hidden = NO;
    self.hidden = NO;
    _button.hidden = YES;
    [self.superview bringSubviewToFront:self];
    _backgroundView.userInteractionEnabled = !_aniamting;
//    [_animatingIV.layer addAnimation:[self animationOut] forKey:kXZLErrorRequestStateViewAnimationKey];

    [_animatingIV startAnimating];

   // [self.animatingOutIV.layer addAnimation:[self animationOut] forKey:nil];
    self.stateLB.text = state ? state : _activityText;
    self.noticeIcon.hidden = YES;
}


- (void)stopAnimating {
    [self stopAnimatingWithHidden:YES];

}


- (void)stopAnimatingWithHidden:(BOOL)hidden
{
    if (_hiding) {
        return;
    }
    _hiding = YES;
    [UIView animateWithDuration:hidden?.1:0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.alpha = hidden?0.f:1.f;
    } completion:^(BOOL finished) {
        _aniamting = NO;
        _hiding = NO;
        _backgroundView.userInteractionEnabled =!_aniamting;
        [_animatingIV stopAnimating];
        [_animatingIV.layer removeAllAnimations];
        [_animatingOutIV.layer removeAllAnimations];
        self.stateLB.text = _errorText;
        self.noticeIcon.hidden = NO;
        self.animatingIV.hidden = YES;
        self.animatingOutIV.hidden = YES;
        _button.hidden = NO;
        self.hidden = hidden;
        _backgroundView.backgroundColor = !hidden?SM_backGroundColor:[UIColor clearColor];
        if (hidden) {
//            [self removeFromSuperview];
        }
    }];
}

- (void)stopAnimatingAtAll {

    [self stopAnimating];
}

- (void)errorNetWorkNoticing {
    [self stopAnimatingWithHidden:NO];
}


#pragma mark - Actions
- (void)onClickView:(UITapGestureRecognizer *)tapG {
    _onClickView && !_aniamting ? [self reStartAnimating] : NULL;
}


- (void)reStartAnimating {
    [self startAnimating:@""];
    _onClickView();

}
@end
